package org.huawei.dao;

import org.huawei.model.domain.Permission;
import org.huawei.utils.DatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PermissionDao {
    public List<Permission> getPermissionsByIds(List<Integer> permissionIds) throws SQLException {
        if (permissionIds.isEmpty()) {
            return Collections.emptyList();
        }

        StringBuilder queryBuilder = new StringBuilder("SELECT * FROM Permission WHERE PermissionId IN (");
        for (int i = 0; i < permissionIds.size(); i++) {
            queryBuilder.append("?");
            if (i < permissionIds.size() - 1) {
                queryBuilder.append(", ");
            }
        }
        queryBuilder.append(")");

        List<Permission> permissions = new ArrayList<>();

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(queryBuilder.toString())) {

            // 设置查询参数
            for (int i = 0; i < permissionIds.size(); i++) {
                stmt.setInt(i + 1, permissionIds.get(i));
            }

            // 执行查询
            ResultSet rs = stmt.executeQuery();

            // 解析结果集，存储权限对象
            while (rs.next()) {
                Permission permission = new Permission();
                permission.setPermissionId(rs.getInt("PermissionId"));
                permission.setPermissionName(rs.getString("PermissionName"));
                permissions.add(permission);
            }
        }
        return permissions;
    }

}
